<?php

namespace App\Listeners;

use App\Events\InstallApp;
use App\Services\InstallService;
use Carbon\Carbon;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\DB;

class CreateAdmin implements ShouldQueue
{

    public function handle(InstallApp $event)
    {
        // 安装完毕后, 动态修改env文件的QUEUE_CONNECTION, 把sync改为redis
        (new InstallService())->editEnv("QUEUE_CONNECTION", "redis");

        $username = session('install.admin_info.admin');
        $password = bcrypt(session("install.admin_info.password"));
        // 新建后台管理员
        DB::table("admin_users")->insert([
            [
                'username' => $username,
                'password' => $password,
                'name' => "Administrator",
                "remember_token" => "4dg3XflECgpqKtzsfFwxaTcTSHree2bMggjiZvUUQbmN7E6kOHHLG9VuO6i1",
                "created_at" => Carbon::now(),
                "updated_at" => Carbon::now(),
            ]
        ]);

        $admin = DB::table('admin_users')
            ->where('username', $username)
            ->where('password', $password)
            ->first();

        // 给这个管理员权限
        DB::table("admin_role_users")->insert([
            [
                'role_id' => 1,
                'user_id' => $admin->id,
                "created_at" => Carbon::now(),
                "updated_at" => Carbon::now(),
            ]
        ]);
    }
}
